#include "bfile.h"
#include <stdio.h>
#include <stdint.h>

BFile::BFile()
{
    file = nullptr;
}

BFile::~BFile()
{
    if (file)
    {
        fclose(file);
        file = nullptr;
    }
}

int BFile::open(const char* fname, const char* mode)
{
    if (fname == nullptr || mode == nullptr)
    {
        return -1;
    }

    file = fopen(fname, mode);
    if (!file)
    {
        perror("Error:");
        return -2;
    }
    return 0;
}

int BFile::close()
{
    if (file)
    {
        fclose(file);
        file = nullptr;
    }

    return  0;
}

int64_t BFile::read(void *ptr, int64_t size, int64_t nmemb)
{
    int64_t ret = 0;
    ret = fread(ptr, size, nmemb, file);
    return ret;
}

int64_t BFile::write(const void *ptr, int64_t size, int64_t nmemb)
{
    int64_t ret = 0;
    ret = fwrite(ptr, size, nmemb, file);
    return ret;
}

int64_t BFile::length()
{
    this->seek(0, SEEK_END);
    int64_t len = this->tell();
    return len;
}

int BFile::seek(int64_t offset, int whence)
{
    int ret = 0;
    ret = fseeko64(file, (off_t)offset, whence);
    if (ret < 0)
    {
        return -1;
    }
    return 0;
}

int64_t BFile::tell()
{
    int64_t offset = 0;
    offset = (int64_t)ftello64(file);
    return offset;
}
